package com.jflm.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * ******************  类说明  *********************
 * class       :  IPUtil
 * @author     :  hejinyun@umpay.com
 * @version    :  1.0  
 * description :  ip地址获取公共处理类
 * @see        :                        
 * ***********************************************
 */
public class IPUtil {

	private static Map<String, String> ipMap = new ConcurrentHashMap<String, String>();
	
	/**
	 * ********************************************
	 * method name   : getRemoteAddress 
	 * description   : 获取远程请求客户端ip地址
	 * @return       : String
	 * @param        : @param request
	 * @param        : @return
	 * modified      : hejinyun@umpay.com ,  2016-11-21  下午6:40:40
	 * @see          : 
	 * *******************************************
	 */
	public static String getRemoteAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	
	public static String getHostAddress(String networkCard){
		String ip = ipMap.get(networkCard);
		if (StringUtils.isNotBlank(ip)){
			return ip;
		}
		try {
			Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
			while (interfaces.hasMoreElements()){
				NetworkInterface networkInterface = interfaces.nextElement();
				if (networkCard.endsWith(networkInterface.getName())){
					Enumeration<InetAddress> netAddress = networkInterface.getInetAddresses();
					while (netAddress.hasMoreElements()){
						InetAddress address = netAddress.nextElement();
						if (address instanceof Inet4Address){
							ip = address.getHostAddress();
							ipMap.put(networkCard, ip);
							return address.getHostAddress();
						}
					}
				}
			}
		} catch (Exception e){
			/*LOG.error("#getHostAddress() 获取本地ip地址异常", e);*/
		}
		return null;
	}
}
